import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:sainbainu/common/values/colors.dart';

import 'package:webview_flutter/webview_flutter.dart';

import 'index.dart';

class UserAgreePage extends GetView<UserAgreeController> {
  const UserAgreePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<UserAgreeController>(
      builder: (_) {
        return Scaffold(
          appBar: _buildAppBar('用户协议'.tr),
          body: _buildBody(),
        );
      },
    );
  }

  /// 头部
  AppBar _buildAppBar(String title) {
    return AppBar(
      title: Text(title),
      leading: IconButton(
        onPressed: () => controller.handleBack(),
        icon: const Icon(Icons.arrow_back_ios),
      ),
      actions: [
        IconButton(
          onPressed: () => controller.handleReload(),
          icon: const Icon(Icons.refresh_rounded),
        ),
      ],
    );
  }

  /// 主视图
  Widget _buildBody() {
    return Obx(() {
      UserAgreeState state = controller.state;
      if (state.error.value) {
        return _buildError(state.errorMsg.value);
      } else if (state.finished.value) {
        return WebViewWidget(controller: state.webViewController);
      } else {
        return _buildLoading();
      }
    });
  }

  /// 加载中
  Widget _buildLoading() {
    return const Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation(AppColors.danger),
      ),
    );
  }

  /// 加载失败
  Widget _buildError(String errorMsg) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(errorMsg),
          const SizedBox(height: 15),
          ElevatedButton(
            onPressed: () => controller.handleReload(),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.danger,
              foregroundColor: Colors.white,
            ),
            child: Text("重试".tr),
          ),
        ],
      ),
    );
  }
}
